<template>
  <div id="basicLayout">
    <el-container style="min-height: 100vh">
      <!-- 左侧菜单栏 -->
      <el-aside :width="isCollapse ? '64px' : '200px'" class="sidebar">
        <div class="logo-container">
          <img class="logo" src="../assets/logo.png" alt="Logo"/>
          <span v-show="!isCollapse" class="logo-text">{{config.projectName}}</span>
        </div>
        <el-menu
            :default-active="activeMenu"
            :collapse="isCollapse"
            :unique-opened="true"
            router
            class="sidebar-menu"
        >
          <template v-for="item in menuItems" :key="item.path">
            <!-- 有子菜单的情况 -->
            <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.path">
              <template #title>
                <el-icon v-if="item.meta?.icon">
                  <component :is="item.meta.icon"/>
                </el-icon>
                <span>{{ item.name }}</span>
              </template>
              <el-menu-item
                  v-for="child in item.children"
                  :key="child.path"
                  :index="child.path"
              >
                <el-icon v-if="child.meta?.icon">
                  <component :is="child.meta.icon"/>
                </el-icon>
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>
            <!-- 没有子菜单的情况 -->
            <el-menu-item v-else :index="item.path">
              <el-icon v-if="item.meta?.icon">
                <component :is="item.meta.icon"/>
              </el-icon>
              <span>{{ item.name }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>

      <el-container>
        <!-- 顶部用户信息栏 -->
        <el-header class="header">
          <div class="header-left">
            <el-button
                type="text"
                @click="toggleCollapse"
                class="collapse-btn"
            >
              <el-icon>
                <component :is="isCollapse ? 'Expand' : 'Fold'"/>
              </el-icon>
            </el-button>
            <!-- 面包屑导航 -->
            <el-breadcrumb separator="/" class="breadcrumb">
              <el-breadcrumb-item
                  v-for="(item, index) in breadcrumbItems"
                  :key="index"
                  :to="item.path"
              >
                {{ item.name }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="header-right">
            <el-space>
              <!-- 主题切换按钮 -->
              <el-button
                  type="text"
                  size="large"
                  @click="toggleTheme"
                  :title="isDarkMode ? '切换到亮色模式' : '切换到暗色模式'"
              >
                <el-icon>
                  <component :is="isDarkMode ? 'Sunny' : 'Moon'"/>
                </el-icon>
              </el-button>

              <!-- 通知图标 -->
              <el-badge :value="3" class="notification-badge">
                <el-button type="text" size="large">
                  <el-icon>
                    <Bell/>
                  </el-icon>
                </el-button>
              </el-badge>

              <!-- 用户头像和下拉菜单 -->
              <el-dropdown @command="handleUserCommand" trigger="click">
                <div class="user-info">
                  <el-avatar :size="32" :src="userAvatar">
                    <el-icon>
                      <User/>
                    </el-icon>
                  </el-avatar>
                  <span class="username">{{ userName }}</span>
                  <el-icon>
                    <ArrowDown/>
                  </el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile">
                      <el-icon>
                        <User/>
                      </el-icon>
                      个人信息
                    </el-dropdown-item>
                    <el-dropdown-item command="settings">
                      <el-icon>
                        <Setting/>
                      </el-icon>
                      系统设置
                    </el-dropdown-item>
                    <el-dropdown-item divided command="logout">
                      <el-icon>
                        <SwitchButton/>
                      </el-icon>
                      退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-space>
          </div>
        </el-header>

        <!-- 标签导航栏 -->
        <div class="tabs-nav">
          <div class="tabs-container">
            <el-tabs
                v-model="activeTab"
                type="card"
                closable
                @tab-click="handleTabClick"
                @tab-remove="handleTabRemove"
                class="tabs-nav-tabs"
            >
              <el-tab-pane
                  v-for="tab in tabs"
                  :key="tab.path"
                  :label="tab.title"
                  :name="tab.path"
                  :closable="tab.path !== '/home'"
              >
                <template #label>
                  <span
                      @contextmenu.prevent="handleTabRightClick($event, tab)"
                      class="tab-label"
                  >
                    {{ tab.title }}
                  </span>
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="tabs-actions">
            <el-dropdown @command="handleTabsCommand" trigger="click">
              <el-button type="text" size="small">
                <el-icon>
                  <MoreFilled/>
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="closeOthers">
                    <el-icon>
                      <Close/>
                    </el-icon>
                    关闭其他
                  </el-dropdown-item>
                  <el-dropdown-item command="closeAll">
                    <el-icon>
                      <Close/>
                    </el-icon>
                    关闭所有
                  </el-dropdown-item>
                  <el-dropdown-item command="refresh">
                    <el-icon>
                      <Refresh/>
                    </el-icon>
                    刷新当前页
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <!-- 主内容区域 -->
        <el-main class="main-content">
          <router-view/>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, watch, onMounted} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {useStore} from 'vuex'
import {appRouter} from '@/router/routes'
import checkAccess from '@/access/checkAccess'
import {logout} from "@/api/user"
import {ElMessage} from 'element-plus'
import { config } from '@/config/index'

const router = useRouter()
const route = useRoute()
const store = useStore()

// 主题模式状态
const isDarkMode = ref(false)

// 菜单折叠状态
const isCollapse = ref(false)

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 用户信息
const userName = computed(() => store.state?.user.loginUser?.userName ?? '未登录')
const userAvatar = computed(() => store.state?.user.loginUser?.avatarUrl ?? '')

// 标签导航相关
const getStoredTabs = () => {
  try {
    const stored = localStorage.getItem(config.tabs)
    return stored ? JSON.parse(stored) : [{path: '/home', title: '首页', name: '首页'}]
  } catch {
    return [{path: '/home', title: '首页', name: '首页'}]
  }
}

const getStoredActiveTab = () => {
  try {
    const stored = localStorage.getItem(config.activeTab)
    return stored || '/home'
  } catch {
    return '/home'
  }
}

const tabs = ref<Array<{ path: string; title: string; name: string }>>(getStoredTabs())
const activeTab = ref(getStoredActiveTab())

// 菜单项
const menuItems = computed(() => {
  return appRouter.filter((item) => {
    if (item.meta?.hideInMenu) {
      return false
    }
    // 根据权限过滤菜单
    if (!checkAccess(store.state.user.loginUser, item?.meta?.access as any)) {
      return false
    }
    return true
  })
})

// 面包屑导航
const breadcrumbItems = computed(() => {
  const items = []
  const currentRoute = route

  // 添加首页
  items.push({name: '首页', path: '/home'})

  // 添加当前页面
  if (currentRoute.name && currentRoute.name !== '首页') {
    items.push({name: currentRoute.name as string, path: currentRoute.path})
  }

  return items
})

// 添加标签
const addTab = (route: any) => {
  const {path, name, meta} = route
  const title = meta?.title || name || '未命名'

  // 检查标签是否已存在
  const existingTab = tabs.value.find(tab => tab.path === path)
  if (!existingTab) {
    // 限制标签数量，最多20个
    if (tabs.value.length >= 20) {
      // 移除最旧的标签（除了首页）
      const nonHomeTabs = tabs.value.filter(tab => tab.path !== '/home')
      if (nonHomeTabs.length > 0) {
        const oldestTab = nonHomeTabs[0]
        removeTab(oldestTab.path)
      }
    }
    tabs.value.push({path, title, name})
  }
  activeTab.value = path
}

// 移除标签
const removeTab = (targetPath: string) => {
  const targetIndex = tabs.value.findIndex(tab => tab.path === targetPath)
  if (targetIndex === -1) return

  tabs.value.splice(targetIndex, 1)

  // 如果关闭的是当前激活的标签，需要跳转到其他标签
  if (activeTab.value === targetPath) {
    let newActivePath = '/home'

    // 优先跳转到右侧标签，如果没有则跳转到左侧标签
    if (tabs.value[targetIndex]) {
      newActivePath = tabs.value[targetIndex].path
    } else if (tabs.value[targetIndex - 1]) {
      newActivePath = tabs.value[targetIndex - 1].path
    }

    activeTab.value = newActivePath
    router.push(newActivePath)
  }
}

// 关闭其他标签
const closeOtherTabs = () => {
  const currentTab = tabs.value.find(tab => tab.path === activeTab.value)
  tabs.value = currentTab ? [currentTab] : [{path: '/home', title: '首页', name: '首页'}]
}

// 关闭所有标签
const closeAllTabs = () => {
  tabs.value = [{path: '/home', title: '首页', name: '首页'}]
  activeTab.value = '/home'
  router.push('/home')
}

// 刷新当前页
const refreshCurrentPage = () => {
  router.go(0)
}

// 监听路由变化，自动添加标签
watch(
    () => route.path,
    (newPath) => {
      if (newPath && !['/user/login', '/user/register', '/403', '/404'].includes(newPath)) {
        addTab(route)
      }
    },
    {immediate: true}
)

// 保存标签页状态到localStorage
const saveTabsState = () => {
  localStorage.setItem(config.tabs, JSON.stringify(tabs.value))
  localStorage.setItem(config.activeTab, activeTab.value)
}

// 监听标签页变化，保存到localStorage
watch(tabs, saveTabsState, {deep: true})
watch(activeTab, saveTabsState)

// 监听主题变化，同步状态
watch(() => document.body.classList.contains('dark'), (isDark) => {
  isDarkMode.value = isDark
}, {immediate: true})

// 主题切换
const toggleTheme = () => {
  if (window.toggleTheme) {
    window.toggleTheme()
    isDarkMode.value = !isDarkMode.value
  }
}

// 切换菜单折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 处理标签点击
const handleTabClick = (tab: any) => {
  if (tab.props.name !== route.path) {
    router.push(tab.props.name)
  }
}

// 处理标签关闭
const handleTabRemove = (targetPath: string) => {
  removeTab(targetPath)
}

// 处理标签操作命令
const handleTabsCommand = (command: string) => {
  switch (command) {
    case 'closeOthers':
      closeOtherTabs()
      break
    case 'closeAll':
      closeAllTabs()
      break
    case 'refresh':
      refreshCurrentPage()
      break
  }
}

// 处理标签右键点击
const handleTabRightClick = (event: MouseEvent, tab: any) => {
  // 这里可以添加右键菜单功能
  console.log('右键点击标签:', tab)
}

// 用户退出登录
const handleUserLogout = async () => {
  try {
    store.commit('userLogout')
    await logout()
  } catch (error) {
    console.error('退出登录失败:', error)
    // ElMessage.error('退出登录失败')
  } finally {
    ElMessage.success('退出登录成功')
    await router.push('/user/login')
  }
}

// 处理用户下拉菜单命令
const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      ElMessage.info('跳转到个人信息页面')
      break
    case 'settings':
      ElMessage.info('跳转到系统设置页面')
      break
    case 'logout':
      await handleUserLogout()
      break
  }
}
</script>

<style scoped>
#basicLayout {
  height: 100vh;
}

/* 侧边栏样式 */
.sidebar {
  background-color: var(--sidebar-bg);
  transition: width var(--transition-duration) var(--transition-timing);
  overflow: hidden;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--logo-bg);
  padding: 0 16px;
}

.logo {
  height: 32px;
  width: 32px;
}

.logo-text {
  color: var(--logo-text);
  font-size: 16px;
  font-weight: bold;
  margin-left: 8px;
  white-space: nowrap;
}

.sidebar-menu {
  border-right: none;
  background-color: var(--sidebar-bg);
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: var(--sidebar-text);
  background-color: var(--sidebar-bg);
}

.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  color: var(--sidebar-text-hover);
  background-color: var(--sidebar-hover);
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  color: var(--sidebar-text-active);
  background-color: var(--sidebar-active);
}

/* 顶部栏样式 */
.header {
  background-color: var(--header-bg);
  border-bottom: 1px solid var(--header-border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.collapse-btn {
  font-size: 18px;
  color: var(--header-text);
}

.collapse-btn:hover {
  color: var(--header-text-hover);
}

.breadcrumb {
  font-size: 14px;
  color: var(--breadcrumb-text);
}

/* 右侧用户信息样式 */
.header-right {
  display: flex;
  align-items: center;
}

.notification-badge :deep(.el-badge__content) {
  background-color: var(--badge-bg);
  color: var(--badge-text);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color var(--transition-duration) var(--transition-timing);
}

.user-info:hover {
  background-color: var(--user-info-hover);
}

.username {
  font-size: 14px;
  color: var(--username-text);
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 标签导航栏样式 */
.tabs-nav {
  background-color: var(--tabs-bg);
  border-bottom: 1px solid var(--tabs-border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 40px;
}

.tabs-container {
  flex: 1;
  overflow: hidden;
}

.tabs-nav-tabs {
  height: 40px;
}

.tabs-nav-tabs :deep(.el-tabs__header) {
  margin: 0;
  border-bottom: none;
}

.tabs-nav-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0;
}

.tabs-nav-tabs :deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
  border: none;
  background-color: transparent;
  color: var(--tabs-text);
  font-size: 14px;
  padding: 0 16px;
  margin-right: 4px;
  border-radius: 4px 4px 0 0;
  transition: all var(--transition-duration) var(--transition-timing);
}

.tabs-nav-tabs :deep(.el-tabs__item:hover) {
  background-color: var(--tabs-bg-hover);
  color: var(--tabs-text-hover);
}

.tabs-nav-tabs :deep(.el-tabs__item.is-active) {
  background-color: var(--tabs-bg-active);
  color: var(--tabs-text-active);
}

.tabs-nav-tabs :deep(.el-tabs__item .el-icon) {
  margin-left: 8px;
  font-size: 12px;
}

.tabs-nav-tabs :deep(.el-tabs__item .el-icon:hover) {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}

.tab-label {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.tabs-actions {
  display: flex;
  align-items: center;
  margin-left: 16px;
}

.tabs-actions .el-button {
  color: var(--tabs-text);
  font-size: 16px;
}

.tabs-actions .el-button:hover {
  color: var(--tabs-text-hover);
}

/* 主内容区域样式 */
.main-content {
  background-color: var(--main-bg);
  color: var(--main-text);
  padding: 20px;
  overflow-y: auto;
}
</style>
